const http = require("http");
const fs = require("fs");
const path = require("path");
// require("./console.js");

const htmlPath = path.resolve(__dirname, "./index.html");
const cssPath = path.resolve(__dirname, "./style/index.css");
const icoPath = path.resolve(__dirname, "./favicon.ico");
const img1Path = path.resolve(__dirname, "./image/img1.jpg");

const server = http.createServer();

server.on("request", (req, res) => {
  // console.log(req)
  console.log("路由地址: ", req.url);
  const route = req.url;
  switch (route) {
    case "/":
      res.setHeader("Content-type", "text.html", "utf-8");
      const htmlData = fs.readFileSync(htmlPath, "utf-8");
      let htmlStr = htmlData.replace(
        /<template><\/template>/g,
        `<div>
  <p>哈哈哈哈</p>
</div>`
      );
      const cssData = fs.readFileSync(cssPath, "utf-8");
      let htmlCssStr = htmlStr.replace(
        "</head>",
        `<style>${cssData}</style></head>`
      );
      res.end(htmlCssStr);

      break;
    case "/favicon.ico":
      const iconData = fs.readFileSync(icoPath);
      res.setHeader("Content-Type", "image/x-icon");
      res.setHeader("Content-Length", iconData.length);

      // 发送图标数据作为响应主体
      res.statusCode = 200;
      res.write(iconData);
      res.end();
      break;
    case "/image/img1.jpg":
      const img1Data = fs.readFileSync(img1Path);
      res.setHeader("Content-type", "image/jpg");
      res.end(img1Data);
      break;
  }
});

server.listen(80, () => {
  console.log("server runing at http://127.0.0.1:80");
});
